package com.example.sprintboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.sprintboot.entity.Order;
import com.example.sprintboot.service.OrderService;
import com.example.sprintboot.vo.OrderDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/orders")
@PreAuthorize("hasRole('ADMIN')")
public class AdminOrderController {

    @Autowired
    private OrderService orderService;

    // 订单列表
    @GetMapping
    public Map<String, Object> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderSn,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        try {
            IPage<Order> result = orderService.adminListOrders(page, pageSize, orderSn, status, userId, startDate, endDate);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", result);
            return response;
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取订单列表失败: " + e.getMessage());
            return response;
        }
    }

    // 获取订单详情
    @GetMapping("/{orderId}/detail")
    public Map<String, Object> getOrderDetail(@PathVariable Integer orderId) {
        try {
            OrderDetailVO orderDetail = orderService.getOrderDetailVO(orderId, null); // 管理员可以查看所有订单
            if (orderDetail == null) {
                return error("订单不存在");
            }
            return success("查询成功", orderDetail);
        } catch (Exception e) {
            return error("查询失败: " + e.getMessage());
        }
    }

    // 强制取消订单
    @PutMapping("/{orderId}/cancel")
    public Map<String, Object> cancelOrder(@PathVariable Integer orderId) {
        try {
            boolean success = orderService.cancelOrderByAdmin(orderId);
            if (success) {
                return success("订单已强制取消");
            } else {
                return error("取消订单失败，订单状态不允许取消");
            }
        } catch (Exception e) {
            return error("取消订单失败: " + e.getMessage());
        }
    }

    // 退款处理
    @PostMapping("/{orderId}/refund")
    public Map<String, Object> refundOrder(@PathVariable Integer orderId, @RequestBody Map<String, Object> req) {
        try {
            String reason = (String) req.get("reason");
            String remark = (String) req.get("remark");
            Double amount = req.get("amount") != null ? Double.valueOf(req.get("amount").toString()) : null;
            
            boolean success = orderService.refundOrderByAdmin(orderId, reason, remark, amount);
            if (success) {
                return success("退款处理成功");
            } else {
                return error("退款处理失败，订单状态不允许退款");
            }
        } catch (Exception e) {
            return error("退款处理失败: " + e.getMessage());
        }
    }

    // 删除订单
    @DeleteMapping("/{orderId}")
    public Map<String, Object> deleteOrder(@PathVariable Integer orderId) {
        try {
            boolean success = orderService.deleteOrderByAdmin(orderId);
            if (success) {
                return success("订单已删除");
            } else {
                return error("删除订单失败，订单状态不允许删除");
            }
        } catch (Exception e) {
            return error("删除订单失败: " + e.getMessage());
        }
    }

    // 获取订单统计数据
    @GetMapping("/stats")
    public Map<String, Object> getOrderStats() {
        try {
            Map<String, Object> stats = orderService.getAdminOrderStats();
            return success("查询成功", stats);
        } catch (Exception e) {
            return error("查询失败: " + e.getMessage());
        }
    }

    // 工具方法
    private Map<String, Object> success(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        return response;
    }

    private Map<String, Object> success(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("data", data);
        return response;
    }

    private Map<String, Object> error(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
} 